package cn.itcast.bos.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototye")
public class AreaAction extends ActionSupport implements ModelDriven<Area> {

	@Autowired
	private AreaService areaService;
	private Area area = new Area();
	private File file;
	
	public void setFile(File file) {
		this.file = file;
	}

	@Override
	public Area getModel() {
		// TODO Auto-generated method stub
		return area;
	}
	
	@Action(value="area_batchImport")
	public void batchImport() throws IOException{
		
		List<Area> list = new ArrayList<Area>();
		// 加载Excel文件
		HSSFWorkbook worbook = new HSSFWorkbook(new FileInputStream(file));
		// 2.读取一个sheet
		HSSFSheet sheet = worbook.getSheetAt(0);
		// 3.读取sheet的每一行
		for (Row row : sheet) {
			System.out.println(row.getRowNum());
			System.out.println(row.getCell(0).getStringCellValue());
			if (row.getRowNum() == 0) {
				continue;
			}
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			Area are = new Area();
			are.setId(row.getCell(0).getStringCellValue());
			are.setProvince(row.getCell(1).getStringCellValue());
			are.setCity(row.getCell(2).getStringCellValue());
			are.setDistrict(row.getCell(3).getStringCellValue());
			are.setPostcode(row.getCell(4).getStringCellValue());
			list.add(are);
		}
		areaService.saveBatch(list);
	}
}
